package services

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"kitalk/models"
)

//是否请求伪造
func IsFakeRequest(sm string) bool {

	return false
}

//MessageService 消息服务
type MessageService struct {
	msg models.WsMessage
	client *Client
}

func (this *MessageService) OnMessage() {
	var chartRecord models.ChartRecord
	var err error
	if this.client.User.Types == 1 {
		chartRecord, err = this.OnCustomer()
	} else {
		chartRecord, err = this.OnManager()
	}

	if err != nil {
		this.Error("OnMessage", err)
		return
	}

	//最终都要给原来的人推送一份
	if err := this.SendChartRecord(chartRecord); err != nil {
		logs.Error("最终都要给原来的人推送一份失败:", err.Error())
	}
}

//OnMessage 接收到顾客消息
func (this *MessageService) OnCustomer() (chartRecord models.ChartRecord, err error) {
	user := this.client.User
	datajson := this.msg.GetDataJson()
	if datajson == "" {
		err = fmt.Errorf("内容不能为空")
		return
	}

	//创建会话
	chart, err := models.ChartCreate(user.Id)
	if err != nil {
		return
	}

	//增加会话记录
	chartRecord = models.ChartRecordAdd(chart.Id, datajson, user.Id, 1)

	//如果有客服，则增加客服未读,并通知客服
	unreadCnt := uint(0)
	if chart.ManagerUid != 0 {
		unreadCnt = models.ChartManagerUnReadAdd(chart.Id, chart.ManagerUid)
	}

	//如果有未读则推送
	if unreadCnt > 0 {
		this.SendChartRecord(chartRecord, chart.ManagerUid)
	}

	return
}

//OnMessage 接收到客服消息
//@params chart_id 会话id
func (this *MessageService) OnManager() (chartRecord models.ChartRecord, err error) {
	chartId := uint(this.msg.GetInt("chart_id"))
	data := this.msg.GetDataJson()
	if chartId == 0 {
		err = fmt.Errorf("会话id不能为0")
		return
	}
	if data == "" {
		err = fmt.Errorf("内容不能为空")
		return
	}

	chart := models.ChartGet(chartId)
	if chart.Id == 0 {
		err = fmt.Errorf("会话不存在")
		return
	}

	//增加会话记录
	user := this.client.User
	chartRecord = models.ChartRecordAdd(chartId, data, user.Id, 2)

	//增加会话未读
	models.ChartUnReadAdd(chartId)

	//通知顾客
	this.SendChartRecord(chartRecord, chart.Uid)

	return
}

//onManagerChart 客服绑定顾客
//@params chart_id 会话id
func (this *MessageService) OnManagerChart() {
	//获取chartId
	chartId := this.msg.GetInt("chart_id")

	chartManager, err := models.ChartManagerAdd(uint(chartId), this.client.User.Id)
	if err != nil {
		this.Error("OnManagerChart", err)
	}

	this.SendChartManager(chartManager)
}
